<template>
  <div class="cart">
    <h2>购物车</h2>
    <ul>
      <li v-for="item in cartItems" :key="item.id">
        {{ item.name }} - ¥{{ item.price }} - 数量: 
        <button @click="decreaseQuantity(item.id)">-</button>
        <input type="number" v-model.number="item.quantity" @change="updateCartItemQuantity(item.id, item.quantity)" />
        <button @click="increaseQuantity(item.id)">+</button>
      </li>
    </ul>
    <p>总价：¥{{ cartTotalPrice }}</p>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex';

export default {
  computed: {
    ...mapState(['cartItems']),
    ...mapGetters(['cartTotalPrice'])
  },
  methods: {
    ...mapActions(['updateCartItemQuantity', 'removeFromCart']),
    increaseQuantity(id) {
      this.updateCartItemQuantity({ id, quantity: this.cartItems.find(item => item.id === id).quantity + 1 });
    },
    decreaseQuantity(id) {
      const item = this.cartItems.find(item => item.id === id);
      if (item.quantity > 1) {
        this.updateCartItemQuantity({ id, quantity: item.quantity - 1 });
      } else {
        this.removeFromCart(id);
      }
    }
  }
};
</script>

<style scoped>
.cart {
  margin: 20px;
  padding: 20px;
  border: 1px solid #ccc;
}
</style>